﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nop.Admin.Models.WindAlert;
using Nop.Admin.WindAlert;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.WindAlert;
using Nop.Services.Directory;
using Nop.Services.ExportImport;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.WindAlert;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Services.Helpers;
using Nop.Web.Framework.Kendoui;
using System.Net;
using System.Text;
using System.IO;

namespace Nop.Admin.Controllers
{
    public partial class WAlertController : BaseAdminController
    {
        #region Fields
        private readonly ILanguageService _languageService;
        private readonly ILocalizationService _localizationService;
        private readonly ILocalizedEntityService _localizedEntityService;
        private readonly ICustomerActivityService _customerActivityService;
        private readonly IExportManager _exportManager;
        private readonly IWorkContext _workContext;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly IUrlRecordService _urlRecordService;
        private readonly IAlertService _alertService;
        private readonly ISpotService _spotService;
        private readonly ICameraService _cameraService;
        private readonly IDateTimeHelper _dateTimeHelper;

        private readonly ICountryService _countryService;
        private readonly IStateProvinceService _stateProvinceService;

        #endregion

        #region Constructors
        
        public WAlertController(ILanguageService languageService,
            ILocalizationService localizationService, ILocalizedEntityService localizedEntityService,
            ICustomerActivityService customerActivityService, 
            IExportManager exportManager, IWorkContext workContext,
            IPermissionService permissionService,
            AdminAreaSettings adminAreaSettings, IUrlRecordService urlRecordService, 
            IAlertService alertService, 
            ISpotService spotService,
            ICameraService cameraService,
            IDateTimeHelper dateTimeHelper
            , ICountryService countryService, IStateProvinceService stateProvinceService)
        {
            this._languageService = languageService;
            this._localizationService = localizationService;
            this._localizedEntityService = localizedEntityService;
            this._customerActivityService = customerActivityService;
            this._exportManager = exportManager;
            this._workContext = workContext;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
            this._urlRecordService = urlRecordService;
            this._alertService = alertService;
            this._spotService = spotService;
            this._cameraService = cameraService;
            this._dateTimeHelper = dateTimeHelper;
            this._countryService = countryService;
            this._stateProvinceService = stateProvinceService;
        }

        #endregion

        #region Utilities

        #endregion

        #region Create / Edit / Delete / List

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            return View();
        }

        [HttpPost]
        public ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            var alerts = _alertService.GetAllSpotsGroups(command.Page - 1, command.PageSize);
            var gridModel = new DataSourceResult
            {
                Data = alerts.Select(x => x.ToModel()),
                Total = alerts.TotalCount
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return AccessDeniedView();

            var model = new SpotsGroupModel();
            //spot
            model.AvailableSpots = _spotService.GetAllSpots()
                .Select(s => s.ToModel())
                .ToList();
            model.SelectedSpotsIds = new int[0];
           
            //default values
            model.Published = true;
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Create(SpotsGroupModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return AccessDeniedView();


            if (ModelState.IsValid)
            {
                var spotsGroup = model.ToEntity();
            
                _alertService.InsertSpotsGroup (spotsGroup);

                //spots
                var allSpots = _spotService.GetAllSpots();
                foreach (var spot in allSpots)
                    if (model.SelectedSpotsIds != null && model.SelectedSpotsIds.Contains(spot.Id))
                        spotsGroup.Spots.Add(spot);
                _alertService.UpdateSpotsGroup(spotsGroup);

                //activity log
                _customerActivityService.InsertActivity("AddNewSpotsGroup", _localizationService.GetResource("ActivityLog.AddNewSpotsGroup"), spotsGroup.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = spotsGroup.Id }) : RedirectToAction("List");
            }

            //cameras
            model.AvailableSpots = _spotService.GetAllSpots()
                .Select(cr => cr.ToModel())
                .ToList();
            model.SelectedSpotsIds = new int[0];

            //default values
            model.Published = true;
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(id);
            if (spotsGroup == null)
                //No spot found with the specified id
                return RedirectToAction("List");

            var model = spotsGroup.ToModel();

            //cameras
            model.AvailableSpots = _spotService
                .GetAllSpots()
                .Select(s => s.ToModel())
                .ToList();
            model.SelectedSpotsIds = spotsGroup.Spots.Select(s => s.Id).ToArray();

            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Edit(SpotsGroupModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(model.Id);
            if (spotsGroup == null)
                //No spot found with the specified id	
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {

                spotsGroup = model.ToEntity(spotsGroup);
               
                _alertService.UpdateSpotsGroup(spotsGroup);
                //spots
                var allSpots = _spotService.GetAllSpots();
                foreach (var spot in allSpots)
                {
                    if (model.SelectedSpotsIds != null &&
                        model.SelectedSpotsIds.Contains(spot.Id))
                    {
                        //new role
                        if (spotsGroup.Spots.Count(s => s.Id == spot.Id) == 0)
                            spotsGroup.Spots.Add(spot);
                    }
                    else
                    {
                        //removed role
                        if (spotsGroup.Spots.Count(s => s.Id == spot.Id) > 0)
                            spotsGroup.Spots.Remove(spot);
                    }
                }
                _alertService.UpdateSpotsGroup(spotsGroup);

                //activity log
                _customerActivityService.InsertActivity("EditSpotsGroup", _localizationService.GetResource("ActivityLog.EditSpotsGroup"), spotsGroup.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Updated"));
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabIndex();

                    return RedirectToAction("Edit", new { id = spotsGroup.Id });
                }
                else
                {
                    return RedirectToAction("List");
                }
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var spotsGroup = _alertService.GetSpotsGroupById(id);
            if (spotsGroup == null)
                //No spot found with the specified id	
                return RedirectToAction("List");
            _alertService.DeleteSpotsGroup(spotsGroup);

            //activity log
            _customerActivityService.InsertActivity("DeleteSpotsGroup", _localizationService.GetResource("ActivityLog.DeleteSpotsGroup"), spotsGroup.Name);

            SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Spots.Deleted"));
            return RedirectToAction("List");
        }
        #endregion

        #region Send notification
        public ActionResult SendNotification()
        {

            return View();
        }
        [HttpPost]
        public ActionResult SendNotification(string message)
        {
            //device token
            string regId = "dsAnbsGTUvI:APA91bF50DgmUHNfCwZ61lzN6ROJ8BLdstu8MydXq3psOUMUJrNsGJ_ijEy6ZNGDAXp8U3CSbxeDR-MFC9yfnfXJSSilxfWSvXtZa_M6slGBlID2j1x4sc9Q6IrZ1PpCRpsVLvUKQSb5";
            var applicationID = "AIzaSyAK1KJa773vD68_IJNAqiFCyqFLfkrmmoQ"; //server API key
            var SENDER_ID = "750321022300"; // Sender id google cunfiguration id windalertandroid

            var value = message;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));


            string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
                + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";


            Console.WriteLine(postData);
            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            tRequest.ContentLength = byteArray.Length;

            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse tResponse = tRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();

            //Label3.Text = sResponseFromServer; //printing response from GCM server.
            tReader.Close();
            dataStream.Close();
            tResponse.Close();



            return View((object)sResponseFromServer);
        }
        #endregion


    }
}
